<template>
  <div class="banner-management">
    <!-- 页面标题和统计卡片 -->
    <lay-card>
      <template #header>
        <div class="page-header">
          <h2>轮播图管理</h2>
          <p>管理系统中的所有轮播图信息</p>
        </div>
      </template>
      <div class="stats-cards">
        <lay-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ bannerStats.totalBanners }}</div>
            <div class="stats-label">总轮播图数</div>
          </div>
        </lay-card>
        <lay-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ bannerStats.activeBanners }}</div>
            <div class="stats-label">启用中</div>
          </div>
        </lay-card>
        <lay-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ bannerStats.inactiveBanners }}</div>
            <div class="stats-label">已禁用</div>
          </div>
        </lay-card>
        <lay-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ bannerStats.expiredBanners }}</div>
            <div class="stats-label">已过期</div>
          </div>
        </lay-card>
      </div>
    </lay-card>

    <!-- 操作区域 -->
    <lay-card style="margin-top: 16px;">
      <lay-row :space="16">
        <lay-col :md="24">
          <lay-button type="primary" @click="handleCreate">
            <lay-icon type="layui-icon-add-1" />
            新增轮播图
          </lay-button>
        </lay-col>
      </lay-row>
    </lay-card>

    <!-- 搜索筛选区域 -->
    <lay-card style="margin-top: 16px;">
      <lay-form :model="searchForm" ref="searchFormRef">
        <lay-row :space="16">
          <lay-col :md="6">
            <lay-form-item label="关键词" prop="keyword">
              <lay-input v-model="searchForm.keyword" placeholder="标题/描述" />
            </lay-form-item>
          </lay-col>
          <lay-col :md="6">
            <lay-form-item label="状态" prop="status">
              <lay-select v-model="searchForm.status" placeholder="请选择状态">
                <lay-select-option value="">全部</lay-select-option>
                <lay-select-option value="1">启用</lay-select-option>
                <lay-select-option value="0">禁用</lay-select-option>
              </lay-select>
            </lay-form-item>
          </lay-col>
          <lay-col :md="6">
            <lay-form-item label="位置" prop="position">
              <lay-select v-model="searchForm.position" placeholder="请选择位置">
                <lay-select-option value="">全部</lay-select-option>
                <lay-select-option value="1">首页顶部</lay-select-option>
                <lay-select-option value="2">首页中部</lay-select-option>
              </lay-select>
            </lay-form-item>
          </lay-col>
        </lay-row>
        <lay-row :space="16">
          <lay-col :md="24">
            <lay-form-item>
              <lay-button type="primary" @click="handleSearch">
                <lay-icon type="layui-icon-search" />
                搜索
              </lay-button>
              <lay-button @click="handleReset" style="margin-left: 8px;">
                <lay-icon type="layui-icon-refresh" />
                重置
              </lay-button>
            </lay-form-item>
          </lay-col>
        </lay-row>
      </lay-form>
    </lay-card>

    <!-- 轮播图列表 -->
    <lay-card style="margin-top: 16px;">
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <span>轮播图列表</span>
          <div>
            <lay-button size="sm" @click="handleExport">
              <lay-icon type="layui-icon-export" />
              导出
            </lay-button>
          </div>
        </div>
      </template>

      <lay-table 
        :columns="columns" 
        :data-source="bannerList" 
        :loading="loading"
        :pagination="false"
        row-key="id"
      >
        <template #image="{ data }">
          <div class="image-preview">
            <img :src="data.image" :alt="data.title" />
          </div>
        </template>

        <template #position="{ data }">
          <lay-tag :type="getPositionTagType(data.position)">
            {{ data.positionText }}
          </lay-tag>
        </template>

        <template #status="{ data }">
          <lay-switch
            :model-value="data.status === 1"
            @update:model-value="(value) => handleStatusChange(data, value)"
            :switch-text="['启用', '禁用']"
          />
        </template>

        <template #start_time="{ data }">
          <span>{{ formatDate(data.startTime) }}</span>
        </template>

        <template #end_time="{ data }">
          <span>{{ formatDate(data.endTime) }}</span>
        </template>

        <template #created_at="{ data }">
          <span>{{ formatDate(data.createdAt) }}</span>
        </template>

        <template #operator="{ data }">
          <lay-button size="xs" @click="handleView(data)">查看</lay-button>
          <lay-button size="xs" type="primary" @click="handleEdit(data)" style="margin-left: 4px;">编辑</lay-button>
          <lay-button 
            size="xs" 
            type="danger" 
            @click="handleDelete(data)" 
            style="margin-left: 4px;"
          >
            删除
          </lay-button>
        </template>
      </lay-table>
      
      <!-- 自定义分页组件 -->
      <Pagination
        :total="pagination.total"
        :page="pagination.current"
        :page-size="pagination.pageSize"
        :page-size-options="pagination.limits"
        @change="handlePaginationChange"
        @update:page="handlePageChange"
        @update:page-size="handlePageSizeChange"
      />
    </lay-card>

    <!-- 轮播图详情/编辑对话框 -->
    <BannerDialog
      v-model="bannerDialogVisible"
      :mode="bannerDialogMode"
      :banner-data="currentBanner"
      @success="handleDialogSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { layer } from '@layui/layui-vue'
import BannerApi from '@/api/module/banner'
import type { Banner as ApiBanner, BannerQueryParams, BannerStatsResponse } from '@/types/banner'
import BannerDialog from './components/BannerDialog.vue'
import Pagination from '@/components/Pagination.vue'

// 轮播图数据类型定义（与后端API一致）
interface Banner {
  id: number
  title: string
  image: string
  linkUrl?: string
  sortOrder: number
  position: number
  status: number
  startTime?: string
  endTime?: string
  createdAt: string
  updatedAt: string
  // 计算属性
  positionText?: string
  statusText?: string
}

interface BannerStats {
  totalBanners: number
  activeBanners: number
  inactiveBanners: number
  expiredBanners: number
}

// 响应式数据
const loading = ref(false)
const bannerList = ref<Banner[]>([])

const bannerDialogVisible = ref(false)
const bannerDialogMode = ref<'view' | 'create' | 'edit'>('view')
const currentBanner = ref<Banner | null>(null)

// 轮播图统计数据
const bannerStats = ref<BannerStats>({
  totalBanners: 0,
  activeBanners: 0,
  inactiveBanners: 0,
  expiredBanners: 0
})

// 搜索表单
const searchForm = reactive<{
  keyword: string
  status: string
  position: string
}>({
  keyword: '',
  status: '',
  position: ''
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showPage: true,
  showCount: true,
  showSkip: true,
  showLimit: true,
  limits: [10, 20, 50, 100]
})

// 表格列配置
const columns = [
  {
    title: '选择',
    width: '60px',
    type: 'checkbox',
    fixed: 'left'
  },
  {
    title: 'ID',
    key: 'id',
    width: '80px'
  },
  {
    title: '图片',
    key: 'image',
    customSlot: 'image',
    width: '120px'
  },
  {
    title: '标题',
    key: 'title',
    minWidth: '150px'
  },
  {
    title: '链接地址',
    key: 'linkUrl',
    minWidth: '200px'
  },
  {
    title: '位置',
    key: 'position',
    customSlot: 'position',
    width: '100px'
  },
  {
    title: '排序',
    key: 'sortOrder',
    width: '80px'
  },
  {
    title: '状态',
    key: 'status',
    customSlot: 'status',
    width: '80px'
  },
  {
    title: '开始时间',
    key: 'startTime',
    customSlot: 'start_time',
    width: '160px'
  },
  {
    title: '结束时间',
    key: 'endTime',
    customSlot: 'end_time',
    width: '160px'
  },
  {
    title: '创建时间',
    key: 'createdAt',
    customSlot: 'created_at',
    width: '160px'
  },
  {
    title: '操作',
    key: 'operator',
    customSlot: 'operator',
    width: '200px',
    fixed: 'right'
  }
]

// 获取轮播图列表
const fetchBannerList = async () => {
  try {
    loading.value = true
    
    // 构建查询参数
    const params: BannerQueryParams = {
      page: pagination.current,
      limit: pagination.pageSize,
      keyword: searchForm.keyword || undefined,
      status: searchForm.status ? parseInt(searchForm.status) : undefined,
      position: searchForm.position || undefined
    }

    // 调用真实API
    const response = await BannerApi.getBannerList(params)
    
    // 处理返回的数据，添加显示用的文本
    // HTTP拦截器返回的是完整响应对象，需要访问response.data.banners
    const processedBanners = response.data.banners.map((banner: ApiBanner) => ({
      ...banner,
      positionText: getPositionText(banner.position),
      statusText: banner.status === 1 ? '启用' : '禁用'
    }))

    bannerList.value = processedBanners
    pagination.total = response.data.total
  } catch (error) {
    layer.msg('获取轮播图列表失败', { icon: 2 })
    console.error('获取轮播图列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取位置显示文本
const getPositionText = (position: number) => {
  const positionMap: Record<number, string> = {
    1: '首页顶部',
    2: '首页中部'
  }
  return positionMap[position] || `位置${position}`
}

// 获取轮播图统计信息
const fetchBannerStats = async () => {
  try {
    const response = await BannerApi.getBannerStats()
    
    // 映射后端返回的统计数据到前端格式
    // HTTP拦截器返回的是完整响应对象，需要访问response.data中的统计字段
    bannerStats.value = {
      totalBanners: response.data.total,
      activeBanners: response.data.active,
      inactiveBanners: response.data.inactive,
      expiredBanners: response.data.expired
    }
  } catch (error) {
    console.error('获取轮播图统计失败:', error)
  }
}

// 分页变化处理
const handlePaginationChange = (page: number, pageSize: number) => {
  pagination.current = page
  pagination.pageSize = pageSize
  fetchBannerList()
}

// 页码变化处理
const handlePageChange = (page: number) => {
  pagination.current = page
  fetchBannerList()
}

// 每页数量变化处理
const handlePageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.current = 1 // 重置到第一页
  fetchBannerList()
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchBannerList()
}

// 重置搜索条件
const handleReset = () => {
  searchForm.keyword = ''
  searchForm.status = ''
  searchForm.position = ''
  pagination.current = 1
  fetchBannerList()
}

// 新增轮播图
const handleCreate = () => {
  currentBanner.value = null
  bannerDialogMode.value = 'create'
  bannerDialogVisible.value = true
}

// 查看轮播图
const handleView = (banner: Banner) => {
  currentBanner.value = banner
  bannerDialogMode.value = 'view'
  bannerDialogVisible.value = true
}

// 编辑轮播图
const handleEdit = (banner: Banner) => {
  currentBanner.value = banner
  bannerDialogMode.value = 'edit'
  bannerDialogVisible.value = true
}

// 删除轮播图
const handleDelete = async (banner: Banner) => {
  try {    
    // 调用删除API
    await BannerApi.deleteBanner(banner.id)
    
    layer.msg('删除成功', { icon: 1 })
    fetchBannerList()
    fetchBannerStats()
  } catch (error) {
    if (error !== 'cancel') {
      layer.msg('删除失败', { icon: 2 })
      console.error('删除轮播图失败:', error)
    }
  }
}

// 状态变化
const handleStatusChange = async (banner: Banner, newStatus: boolean) => {
  try {
    const status = newStatus ? 1 : 0
    
    // 调用更新状态API
    await BannerApi.updateBannerStatus(banner.id, status)
    
    banner.status = status
    banner.statusText = status === 1 ? '启用' : '禁用'
    layer.msg('状态更新成功', { icon: 1 })
    fetchBannerStats()
  } catch (error) {
    layer.msg('状态更新失败', { icon: 2 })
    console.error('更新轮播图状态失败:', error)
    // 恢复原状态
    banner.status = banner.status === 1 ? 0 : 1
  }
}

// 导出
const handleExport = () => {
  layer.msg('导出功能开发中...', { icon: 3 })
}

// 对话框成功回调
const handleDialogSuccess = () => {
  fetchBannerList()
  fetchBannerStats()
}

// 获取位置标签类型
const getPositionTagType = (position: number) => {
  const typeMap: Record<number, string> = {
    1: 'primary',
    2: 'normal'
  }
  return typeMap[position] || 'normal'
}

// 格式化日期
const formatDate = (dateString: string | undefined) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 页面加载时获取数据
onMounted(() => {
  fetchBannerList()
  fetchBannerStats()
})
</script>

<style scoped>
.banner-management {
  padding: 16px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 20px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-top: 16px;
}

.stats-card {
  text-align: center;
}

.stats-content {
  padding: 20px;
}

.stats-number {
  font-size: 28px;
  font-weight: bold;
  color: #1890ff;
  margin-bottom: 8px;
}

.stats-label {
  font-size: 14px;
  color: #666;
}

.image-preview {
  width: 80px;
  height: 45px;
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #e8e8e8;
}

.image-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>